package com.springboot.service;

import com.springboot.dao.SysRoleDao;
import com.springboot.dao.SysUserDao;
import com.springboot.domain.SysRole;
import com.springboot.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class JdbcUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysRoleDao sysRoleDao;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据username获取SysUser
        SysUser user = sysUserDao.selectSysUser(username);
        System.out.println(user);

        if (user != null){
            //根据userId，获取role
            List<SysRole> roleList = sysRoleDao.selectRoleByUser(user.getId());

            List<GrantedAuthority> authorities = new ArrayList<>();

            String roleName = "";
            for (SysRole role : roleList) {

                roleName = role.getRolename();
                System.out.println(roleName);
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + roleName);
                authorities.add(authority);
            }
            user.setAuthorities(authorities);
            return user;
        }
        return user;

    }
}
